<?php

/**
 * 文档 - 数据模型
 * 
 * @package    01CMS
 * @subpackage admin
 * @author     rolong at vip.qq.com
 * @version    1.0.0
 * @link       http://www.01cms.com
 */

class ArchiveModel
{
    public $id;
    public $data;
    
    private $Db;

    function __construct ($id = 0)
    {
        $this->Db = model('Db');
        
        if ($id > 0)
        {
            $this->id = $id;
            $this->data = $this->getArchiveById($id);
        }
    }

    /**
     * 通过文档ID获取文档
     * 
     * @param int $id
     * @return object
     * @access public
     */
    function getArchiveById ($id)
    {
        return $this->Db->getRow("SELECT * FROM @@__archive_archive where id={$id}");
    }

    /**
     * 获取文档ID，主要用于HTML更新
     * 
     * @param string $where
     * @param int $page
     * @param int $pageSize
     * @return object
     * @access public
     */
    function getArchiveIds ($where = 1, $page = 1, $pageSize = 20)
    {
        $start = ($page - 1) * $pageSize;
        
        return $this->Db->getRows("SELECT id FROM @@__archive_archive WHERE {$where} LIMIT {$start}, {$pageSize}");
    }

    /**
     * 计算文档总数，用于HTML更新
     * 
     * @param string $where
     * @return int
     * @access public
     */
    function countArchives ($where = 1)
    {
        return  $this->Db->getOne("SELECT count(*) FROM @@__archive_archive WHERE pass = 1 AND {$where}");
    }

    /**
     * 获取文档列表
     * 
     * @param array $params
     * @return object
     * @access public
     */
    function getArchives ($params)
    {
        $start = empty($params['start']) ? 0 : $params['start'];
        $whereFlag = empty($params['flag']) ? '' : "and FIND_IN_SET('{$params['flag']}',flag)>0";
        $size = empty($params['size']) ? 30 : $params['size'];
        $order = empty($params['order']) ? 'ordering desc' : $params['order'];
        if (empty($params['categoryId']))
        {
            $whereCategoryId = '';
        }
        else
        {
            $Category = model('Category');
            $Category->categoryIds = '';
            $Category->getChildIds($params['categoryId'], TRUE);
            $whereCategoryId = empty($Category->categoryIds) ? "and categoryId = {$params['categoryId']}" : "and categoryId in ({$params['categoryId']},{$Category->categoryIds})";
        }
        
        return $this->Db->getRows("SELECT * FROM @@__archive_archive where pass = 1 $whereCategoryId $whereFlag order by $order limit {$start}, {$size}");
    }

    /**
     * 处理文档属性
     * 
     * @param array $lists
     * @return array
     * @access public
     */
    function setArchiveFlag ($lists)
    {
        $count = count($lists);
        
        for ($i = 0; $i < $count; $i ++)
        {
            $Category = model('Category',$lists[$i]->categoryId);
            $lists[$i]->title = htmlspecialchars($lists[$i]->title);
            
            $flag = explode(',', $lists[$i]->flag);
            
            if (in_array('p', $flag))
            {
                $lists[$i]->title .= '[图]';
            }
            
            $lists[$i]->categoryName = $Category->name;
            
            if (in_array('b', $flag))
            {
                $lists[$i]->title = '<b>' . $lists[$i]->title . '</b>';
            }
            
            if (! empty($lists[$i]->color) && $lists[$i]->color != '#000000')
            {
                $lists[$i]->title = '<font color="' . $lists[$i]->color . '">' . $lists[$i]->title . '</font>';
            }
            
            if (in_array('j', $flag))
            {
                $lists[$i]->staticUrl = $lists[$i]->activeUrl = $lists[$i]->url = $lists[$i]->redirectUrl;
            }
            else
            {
                $staticUrl = empty($lists[$i]->fileName) ? $Category->archiveUrl : $lists[$i]->fileName;
                
                $staticUrl = str_replace('[id]', $lists[$i]->id, $staticUrl);
                $staticUrl = str_replace('[alias]', $Category->alias, $staticUrl);
                $staticUrl = str_replace('%Y', date('Y', $lists[$i]->addTime), $staticUrl);
                $staticUrl = str_replace('%m', date('m', $lists[$i]->addTime), $staticUrl);
                $staticUrl = str_replace('%d', date('d', $lists[$i]->addTime), $staticUrl);
				$staticUrl = ROOT_DIR . $staticUrl;
                $lists[$i]->staticUrl = $staticUrl;
                $lists[$i]->activeUrl = BOOT_URL . '/data/archive/' . $lists[$i]->id;
                $lists[$i]->url = defined('staticHtml') ? $staticUrl : $lists[$i]->activeUrl;
            }
        }
        
        return $lists;
    }

    /**
     * 添加文档
     * 
     * @param array $data
     * @param array $addData
     * @param string $tableId
     * @return bool
     * @access public
     */
    function insertArchive ($data, $addData, $tableId)
    {
        $addData['archiveId'] = $this->Db->insert($data, '@@__archive_archive');
        
        $addData['categoryId'] = $data['categoryId'];
        
        $pageDelimiter = addslashes(Base::i()->Load->var['pageDelimiter']);
        
        $channelTables = explode(',', Base::i()->Load->var['pagesContentChannel']);
        
        $isPages = in_array($tableId, $channelTables) ? 1 : 0;
        
        if ($isPages && strpos($addData['content'], $pageDelimiter) !== FALSE)
        {
            $items = explode($pageDelimiter, $addData['content']);
            
            foreach ($items as $item)
            {
                $addData['content'] = $item;
                $this->Db->insert($addData, '@@__archive_channel_' . $tableId);
            }
        }
        else
        {
            $this->Db->insert($addData, '@@__archive_channel_' . $tableId);
        }
    }

    /**
     * 更新文档
     * 
     * @param array $data
     * @param array $addData
     * @param string $tableId
     * @param int $id
     * @return bool
     * @access public
     */
    function updateArchive ($data, $addData, $tableId, $id)
    {
        $this->Db->update($data, "id={$id}", '@@__archive_archive');
        
        $pageDelimiter = addslashes(Base::i()->Load->var['pageDelimiter']);
        
        $channelTables = explode(',', Base::i()->Load->var['pagesContentChannel']);
        
        $isPages = in_array($tableId, $channelTables) ? 1 : 0;
        
        if ($isPages && strpos($addData['content'], $pageDelimiter) !== FALSE)
        {
            $items = explode($pageDelimiter, $addData['content']);
            $ids = $this->Db->getRows("SELECT id, archiveId, categoryId FROM @@__archive_channel_{$tableId} where archiveId={$id}");
            $countItems = count($items);
            $countIds = count($ids);
            for ($i = 0; $i < $countItems; $i ++)
            {
                if ($i < $countIds)
                {
                    $addData['content'] = $items[$i];
                    $this->Db->update($addData, "id={$ids[$i]->id}", '@@__archive_channel_' . $tableId);
                }
                else
                {
                    $addData['archiveId'] = $ids[0]->archiveId;
                    $addData['categoryId'] = $ids[0]->categoryId;
                    $addData['content'] = $items[$i];
                    $this->Db->insert($addData, '@@__archive_channel_' . $tableId);
                }
            
            }
            
            if ($countIds > $countItems)
            {
                $limitNum = $countIds - $countItems;
                
                $this->Db->query("delete from @@__archive_channel_{$tableId} order by id desc limit {$limitNum}");
            }
        }
        else
        {
            $this->Db->update($addData, "archiveId={$id}", '@@__archive_channel_' . $tableId);
        }
    }

    function delArchive ($ids)
    {
        $items = explode(',', $ids);
        
        $category = data('archiveCategory');
        $channel = data('archiveChannel');
        
        foreach ($items as $id)
        {
            $archive = $this->getArchiveById($id);
            $curCategory = $category[$archive->categoryId];
            $curChannel = $channel[$curCategory['channelId']];
            $this->Db->del("id={$id}", '@@__archive_archive');
            $this->Db->del("archiveId={$id}", '@@__archive_channel_' . $curChannel['tableId']);
        }
    }

    public function __get ($key)
    {
        if(isset($this->$key))
        {
            return $this->$key;
        }
        else if(isset($this->data->$key))
        {
            return $this->data->$key;
        }
        else 
        {
            return '';
        }
    }
}